<template>
  <div class="login-container">

    <div class="login-form">
      <!-- <div class="lang-box"
           @click="switchLang(lang)">
        <div class="lang-cn lang-btn "
             :class="lang==='zh'?'lang-act':''">
          中文
        </div>
        <div class="lang-en lang-btn"
             :class="lang==='en'?'lang-act':''">
          EN
        </div>
      </div> -->

      <div class="form-mid">
        <div class="logo-box">
          <img src="~@/assets/imgs/login/logo-blue.png"
               alt="量准logo">
        </div>

        <!-- <div class="login-tabs">
          <div class="login-tab tab-left"
               :class="loginType==='2'?'tab-act':''"
               @click="hanldeRegTabs">{{$t('page.register')}}</div>
          <div class="login-tab tab-right"
               :class="loginType==='1'?'tab-act':''"
               @click="hanldeLoginTabs">{{$t('page.login')}}</div>
        </div> -->
        <el-form ref="loginForm"
                 :model="loginForm"
                 :rules="loginRules"
                 auto-complete="on"
                 label-position="left">
          <div class="login-input">
            <el-form-item prop="username"
                          v-if="lang==='en'">
              <span class="svg-container"
                    v-if="loginType==='1'">
                <svg-icon icon-class="email" />
              </span>
              <el-input v-model="loginForm.username"
                        type="text"
                        auto-complete="on"
                        :placeholder="$t('page.fillEmail')" />
            </el-form-item>
            <el-form-item v-if="lang==='zh'"
                          prop="phone">
              <span class="svg-container"
                    v-if="loginType==='1'">
                <svg-icon icon-class="phone" />
              </span>
              <el-input v-model="loginForm.phone"
                        type="text"
                        auto-complete="on"
                        :placeholder="$t('page.fillPhone')" />
            </el-form-item>

            <template v-if="lang==='zh'">
              <el-form-item prop="code">
                <span class="svg-container">
                  <svg-icon icon-class="code" />
                </span>
                <el-input v-model="loginForm.code"
                          name="code"
                          type="text"
                          placeholder="验证码"></el-input>
                <el-button type="text"
                           @click="getCode"
                           class="get-code"
                           v-show="!computedTime">获取验证码</el-button>
                <el-button type="text"
                           class="get-code"
                           v-show="computedTime">已发送({{computedTime}}s)</el-button>
              </el-form-item>
            </template>
            <!-- <el-form-item prop="password">
              <span class="svg-container"
                    v-if="loginType==='1'">
                <svg-icon icon-class="password" />
              </span>
              <el-input :type="pwdType"
                        v-model="loginForm.password"
                        name="password"
                        auto-complete="on"
                        :placeholder="$t('page.fillPass')"
                        @keyup.enter.native="handleLogin" />
            </el-form-item>
            <el-form-item prop="repassword"
                          v-if="loginType==='2'">
              <el-input :type="pwdType"
                        v-model="loginForm.repassword"
                        name="password"
                        auto-complete="on"
                        :placeholder="$t('page.fillPass')" />
            </el-form-item> -->
            <el-form-item>
              <!-- <el-button :loading="loading"
                         type="primary"
                         style="width:100%;"
                         @click.native.prevent="handleLogin"
                         v-if="loginType==='1'">
                {{$t('page.login')}}
              </el-button> -->
              <el-button :loading="loading"
                         type="primary"
                         style="width:100%;"
                         @click.native.prevent="handlePhoneLogin"
                         v-if="lang==='zh'">
                {{$t('page.login')}}
              </el-button>
              <el-button :loading="loading"
                         type="primary"
                         style="width:100%;"
                         @click.native.prevent="handleSubmit('loginForm')"
                         v-if="loginType==='2'">
                {{$t('page.register')}}
              </el-button>
            </el-form-item>
            <!-- <div class="forget-pwd"
                 @click="handleForget"
                 v-if="lang==='en'">
              {{$t('page.forget')}}
            </div> -->
          </div>
        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
import { login, register, fetchCode, resetPwd, registerMail } from '@/api/login'
import md5 from 'md5'
import { setStore, getStore } from '@/utils/common'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('page.emailVal')))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('page.passVal')))
      } else {
        callback()
      }
    }
    const validateRepass = (rule, value, callback) => {
      if (value !== this.loginForm.password) {
        callback(new Error(this.$t('page.rePassVal')))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('page.phoneVal')))
      } else {
        callback()
      }
    }
    const validateCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t('page.codeVal')))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        repassword: '',
        phone: '',
        code: '',
      },
      loginRules: {
        phone: [
          {
            required: true,
            trigger: 'blur',
            validator: validatePhone,
          },
        ],
        username: [
          {
            required: true,
            trigger: 'blur',
            validator: validateUsername,
          },
        ],
        password: [
          { required: true, trigger: 'blur', validator: validatePass },
        ],
        repassword: [
          { required: true, trigger: 'blur', validator: validateRepass },
        ],
        code: [{ required: true, trigger: 'blur', validator: validateCode }],
      },
      loading: false,
      pwdType: 'password',
      redirect: undefined,
      computedTime: 0,
      timer: 0,
      loginType: '1',
      lang: getStore('spr-lang') || 'zh',
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },
  },
  methods: {
    reset() {
      if (this.$refs['loginForm']) {
        this.$refs['loginForm'].resetFields()
      }
    },
    async handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (this.loginForm.phone) {
            this.loginForm.username = this.loginForm.phone
          }
          let formData = {}
          // this.loading = true;
          formData.password = this.loginForm.password
          formData.loginName = this.loginForm.username
          this.$store
            .dispatch('Login', formData)
            .then(() => {
              this.loading = false
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    async handlePhoneLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          let formData = {}
          // this.loading = true;
          formData.userName = this.loginForm.phone
          formData.code = this.loginForm.code
          this.$store
            .dispatch('SmsLogin', formData)
            .then(() => {
              this.loading = false
              this.$router.push({ path: this.redirect || '/' })
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    async getCode() {
      if (this.loginForm.phone.length == 11) {
        this.computedTime = 60
        this.timer = setInterval(() => {
          this.computedTime--
          if (this.computedTime == 0) {
            clearInterval(this.timer)
          }
        }, 1000)
        const res = await fetchCode({
          phone: this.loginForm.phone,
        })
        this.$message.success(this.$t('page.send_success'))
      }
    },
    handleSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.loginType === '2') {
            this.fetchRegisterMail(formName)
          } else if (this.loginType === '3') {
            this.fetchResetPwd(formName)
          }
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    async fetchRegisterMail(formName) {
      if (this.loginForm.phone) {
        this.loginForm.username = this.loginForm.phone
      }
      const res = await register({
        loginName: this.loginForm.username,
        password: this.loginForm.password,
      })
      this.$message.success(this.$t('page.register_success'))
      this.resetForm(formName)
    },
    switchLang(lang) {
      this.reset()
      if (lang === 'zh') {
        this.switchEnlish()
        document.title = 'Xlement Management System'
      } else {
        this.switchChinese()
        document.title = '量准云计算平台'
      }
    },
    handleForget() {},
    hanldeLoginTabs(type) {
      this.loginType = '1'
      this.reset()
    },
    hanldeRegTabs(type) {
      this.loginType = '2'
      this.reset()
    },
    switchChinese() {
      this.$i18n.locale = 'zh'
      setStore('LZ-lang', 'zh')
      this.lang = getStore('LZ-lang')
    },
    switchEnlish() {
      this.$i18n.locale = 'en'
      setStore('LZ-lang', 'en')
      this.lang = getStore('LZ-lang')
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/theme/mixin';
.login-container {
  // position: fixed;
  height: 100%;
  width: 100%;
  display: flex;
  .login-img {
    width: 60vw;
    // background: url('~@/assets/login-bg.jpg') no-repeat;
    background-size: cover;
    position: relative;
    .login-product {
      position: absolute;
      bottom: 17px;
      width: 100%;
      display: flex;
      img {
        width: 100%;
      }
      .product-img {
        flex: 1;
        width: 100%;
        background-color: #1681f1;
        border-radius: 15px;
        padding: 40px 15px;
        margin: 15px;
        transition-duration: 0.3s;
      }
      .product-img:hover {
        box-shadow: 8px 5px 20px rgba($color: #000, $alpha: 1);
      }
      .txt {
        margin-top: 10px;
        font-size: 14px;
        color: #fff;
        text-align: center;
      }
    }
  }
  .login-form {
    right: 0;
    width: 40vw;
    background: #fff;
  }
  .login-input {
    position: relative;
    width: 360px;
    margin: 0 auto 1vh;
  }
  .form-mid {
    position: absolute;
    width: 100%;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
  }
  .logo-box {
    margin: 0 auto 8vh auto;
    width: 138px;
    img {
      width: 100%;
    }
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 4px 5px 6px 15px;
    color: $blue;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title {
    font-size: 26px;
    font-family: Helvetica;
    color: $blue;
    margin: 0 auto 10vh auto;
    text-align: center;
    padding: 0 10px;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $blue;
    cursor: pointer;
    user-select: none;
  }
}

.find-pwd {
  text-align: center;
  &-btn {
    color: #fff;
  }
}
.login-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  text-align: center;
}
.login-text {
  color: #fff;
  font-size: 20px;
}
.get-code {
  float: left;
  text-align: center;
  padding: 0 12px;
}
.lang-box {
  position: absolute;
  right: 20px;
  top: 20px;
  display: flex;
  z-index: 999;
}

.lang-btn {
  width: 55px;
  padding: 4px 0;
  background: #fff;
  color: #a8d2fe;
  border: 1px solid #a8d2fe;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
}
.lang-act {
  background: #515457;
  border: 1px solid $blue;
}
.login-tabs {
  position: relative;
  display: flex;
  width: 360px;
  margin: auto;
}
.login-tab {
  width: 50%;
  height: 45px;
  line-height: 45px;
  text-align: center;
  color: #c5c7cb;
  border: 1px solid #dedede;
  font-size: 16px;
  font-family: MicrosoftYaHei;
  margin-bottom: 4vh;
  cursor: pointer;
}
.tab-right {
  border-radius: 0px 6px 6px 0px;
}
.tab-left {
  border-radius: 6px 0px 0px 6px;
}
.tab-act {
  color: #fff;
  background: #3e4651;
  border: 1px solid #3e4651;
}
.forget-pwd {
  color: #d04a4a;
  font-size: 14px;
  text-align: right;
  cursor: pointer;
}
</style>

<style lang="scss">
$bg: #fafafa;
/* reset element-ui css */
.login-container {
  .el-input {
    // display: inline-block;
    height: 47px;
    // width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #000 !important;
      }
    }
  }
  .el-form-item {
    line-height: 35px;
    border: 1px solid #c5c7cb;
    background: #fafafa;
    border-radius: 5px;
    color: #454545;
    input {
      height: 100%;
    }
  }
  .el-form-item__content {
    display: flex;
  }
}
</style>